package com.zshan.clinic.admin.service.clinic;

import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.dto.ResetPasswordDTO;
import com.zshan.clinic.admin.entity.medical.emp.ClinicEmpSimple;
import com.zshan.clinic.admin.entity.dto.ClinicEmpDTO;
import com.zshan.clinic.admin.entity.vo.ClinicEmpInfoVo;
import com.zshan.clinic.admin.entity.vo.ClinicEmpSelectVo;
import com.zshan.clinic.admin.entity.vo.ClinicEmpSignatureVo;
import com.zshan.clinic.admin.entity.vo.ClinicEmpVo;
import com.zshan.clinic.admin.mapper.clinic.SpecClinicEmpMapper;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.enums.GenderEnum;
import com.zshan.clinic.common.enums.OperateTypeEnum;
import com.zshan.clinic.common.enums.PasswordChangeSourceEnum;
import com.zshan.clinic.common.enums.YesOrNoEnum;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.crypto.CryptoUtils;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.uuid.IdBuilder;
import com.zshan.clinic.common.util.validate.BankCardValidator;
import com.zshan.clinic.common.util.validate.EmailValidator;
import com.zshan.clinic.common.util.validate.IdCardUtils;
import com.zshan.clinic.common.util.validate.PhoneValidator;
import com.zshan.clinic.database.dao.ClinicEmpMapper;
import com.zshan.clinic.database.dao.ClinicEmpSignatureMapper;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工
 */
@Service
@Slf4j
public class ClinicEmpService {

    @Autowired
    private ClinicEmpMapper clinicEmpMapper;

    @Autowired
    private ClinicEmpSignatureMapper clinicEmpSignatureMapper;

    @Autowired
    private SpecClinicEmpMapper specClinicEmpMapper;

    @Autowired
    private ClinicAuthService clinicAuthService;

    @Autowired
    private ClinicDeptService clinicDeptService;

    /**
     * 维护医生签名
     * @param clinicEmpSignature
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSignature(ClinicEmpSignature clinicEmpSignature){
        if(StringUtil.isBlank(clinicEmpSignature.getSignature())){
            throw new BusinessFailException("请先维护签名！");
        }
        ClinicEmpSignature dbClinicEmpSignature = getClinicEmpSignature(clinicEmpSignature.getClinicId(), clinicEmpSignature.getEmpId());
        if(dbClinicEmpSignature == null){
            clinicEmpSignature.setIsEnabled(YesOrNoEnum.YES.getValue());
            clinicEmpSignature.setIsDelete(YesOrNoEnum.NO.getValue());
            clinicEmpSignature.setCreateTime(new Date());
            clinicEmpSignatureMapper.insertSelective(clinicEmpSignature);
        }else {
            dbClinicEmpSignature.setSignature(clinicEmpSignature.getSignature());
            dbClinicEmpSignature.setUpdateUserId(clinicEmpSignature.getUpdateUserId());
            dbClinicEmpSignature.setUpdateBy(clinicEmpSignature.getUpdateBy());
            dbClinicEmpSignature.setUpdateTime(new Date());
            clinicEmpSignatureMapper.updateByPrimaryKeySelective(dbClinicEmpSignature);
        }
    }
    /**
     * 获取医生签名
     * @param clinicId
     * @param empId
     * @return
     */
    public ClinicEmpSignatureVo getEmpSignature(Long clinicId, Long empId){
        ClinicEmpSignatureVo clinicEmpSignatureVo = new ClinicEmpSignatureVo();
        clinicEmpSignatureVo.setEmpId(empId);
        ClinicEmpSignature empSignature = getClinicEmpSignature(clinicId,empId);
        if(empSignature != null){
            clinicEmpSignatureVo.setSignature(empSignature.getSignature());
        }
        return clinicEmpSignatureVo;
    }


    public ClinicEmpSignature getClinicEmpSignature(Long clinicId, Long empId){
        ClinicEmpSignatureExample example = new ClinicEmpSignatureExample();
        ClinicEmpSignatureExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andEmpIdEqualTo(empId);
        criteria.andSignatureIsNotNull();
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        List<ClinicEmpSignature> signatureList = clinicEmpSignatureMapper.selectByExample(example);
        return CollectionUtils.isEmpty(signatureList) ? null : signatureList.get(0);
    }

    /**
     * 工作台：获取员工个人信息
     * @param clinicId
     * @param empId
     * @return
     */
    public ClinicEmpInfoVo getEmpInfo(Long clinicId, Long empId) {
        return specClinicEmpMapper.getEmpInfo(clinicId,empId);
    }

    /**
     * 获取员工下拉框数据
     * @param clinicId
     * @return
     */
    public List<ClinicEmpSelectVo> getSelectList(Long clinicId){
        List<ClinicEmp> empList = getEmpListByClinicId(clinicId);
        if(CollectionUtils.isEmpty(empList)){
            return Collections.EMPTY_LIST;
        }
        // 将实体列表转换为DTO列表
        return empList.stream().map(emp -> {
            ClinicEmpSelectVo selectVo = new ClinicEmpSelectVo();
            BeanUtils.copyProperties(emp, selectVo);
            return selectVo;
        }).collect(Collectors.toList());
    }

    /**
     * 查询诊所的员工
     * @param clinicId
     * @return
     */
    public List<ClinicEmp> getEmpListByClinicId(Long clinicId) {
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsEnabledEqualTo(YesOrNoEnum.YES.getValue());
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return clinicEmpMapper.selectByExample(example);
    }

    /**
     * 查询员工简要信息
     * @param empId
     * @return
     */
    public ClinicEmpSimple getEmpSimple(Long clinicId, Long empId){
        return specClinicEmpMapper.getEmpSimple(clinicId,empId);
    }

    /**
     * 查询诊所的员工列表
     *
     * @param clinicId
     * @param empName
     * @param deptId
     * @param roleId
     * @return
     */
    public PageInfo<ClinicEmpVo> getClinicEmpList(Long clinicId, String empName, Long deptId, Long roleId,Integer pageNo,Integer pageSize){
        Long totalCount = specClinicEmpMapper.getClinicEmpCount(clinicId,empName,deptId,roleId);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<ClinicEmpVo> empList = specClinicEmpMapper.getClinicEmpList(clinicId,empName,deptId,roleId, PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,empList);
    }


    /**
     * 获取员工详情
     * @param clinicId
     * @param empId
     * @return
     */
    public ClinicEmpVo getEmpDetail(Long clinicId, Long empId) {
        return specClinicEmpMapper.getEmpDetail(clinicId,empId);
    }

    /**
     * 查询诊所管理员
     * @param clinicId
     * @return
     */
    public ClinicEmp getClinicAdmin(Long clinicId){
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andIsAdminEqualTo(YesOrNoEnum.YES.getValue());
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        List<ClinicEmp> clinicEmpList = clinicEmpMapper.selectByExample(example);
        return CollectionUtils.isEmpty(clinicEmpList) ? null : clinicEmpList.get(0);
    }

    /**
     * 添加员工
     * @param clinicEmp
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(ClinicEmpDTO clinicEmp){
        validateEmp(clinicEmp,clinicEmp.getIsAdmin());
        if(StringUtil.isBlank(clinicEmp.getPassword())){
            clinicEmp.setPassword(CryptoUtils.md5(Constants.DEFAULT_PASS));
        }
        clinicEmp.setEmpNo(getEmpNo(clinicEmp.getClinicId()));
        clinicEmp.setIsEnabled(YesOrNoEnum.YES.getValue());
        clinicEmp.setIsDelete(YesOrNoEnum.NO.getValue());
        clinicEmp.setCreateTime(new Date());
        clinicEmpMapper.insertSelective(clinicEmp);
        //保存员工角色数据
        clinicAuthService.authUserRoles(clinicEmp);
        //更新部门员工数量
        refreshEmpCount(clinicEmp.getClinicId(),clinicEmp.getDeptId());
    }

    /**
     * 获取下一个员工号
     * @param clinicId
     * @return
     */
    private String getEmpNo(Long clinicId) {
        String maxEmpNo = specClinicEmpMapper.getMaxEmpNo(clinicId);
        if(StringUtil.isBlank(maxEmpNo)){
            maxEmpNo = Constants.DEFAULT_EMP_NO;
        }
        return IdBuilder.nextNo(maxEmpNo);
    }

    public void validateEmp(ClinicEmpDTO clinicEmp,String isAdmin){
        clinicEmp.setEmpName(StringUtil.removeAllWhitespace(clinicEmp.getEmpName()));
        if(StringUtil.isBlank(clinicEmp.getEmpName())){
            throw new BusinessFailException("员工名不能为空");
        }
        if(clinicEmp.getEmpName().length() > Constants.EMP_LENGTH){
            throw new BusinessFailException("员工名"+Constants.EMP_LENGTH+"个字以内！");
        }
        if(StringUtil.isBlank(clinicEmp.getPhone())){
            throw new BusinessFailException("联系方式不能为空");
        }
        if(!PhoneValidator.isValidMobile(clinicEmp.getPhone())){
            throw new BusinessFailException("手机号格式错误！");
        }
        if(StringUtil.isBlank(clinicEmp.getGender())){
            clinicEmp.setGender(GenderEnum.UNKNOWN.getValue());
        }
        if(!GenderEnum.isValue(clinicEmp.getGender())){
            throw new BusinessFailException("性别错误！");
        }
        //根据手机号查询员工信息
        Long empCount = getEmpCountByPhone(clinicEmp.getClinicId(),clinicEmp.getEmpId(),clinicEmp.getPhone());
        if(empCount > CommonConstant.DEFAULT_0){
            throw new BusinessFailException("当前手机号已被占用，请更换手机号再试！");
        }
        if(StringUtil.isBlank(clinicEmp.getIsAdmin())){
            clinicEmp.setIsAdmin(YesOrNoEnum.NO.getValue());
        }
        if(StringUtil.isBlank(clinicEmp.getAvatarUrl())){
            //默认头像
            clinicEmp.setAvatarUrl(Constants.DEFAULT_AVATAR);
        }
        //根据手机号查询其他诊所的信息，因为现在还不支持切换登录
        Long empOtherCont = getOtherEmpByPhone(clinicEmp.getPhone(),clinicEmp.getClinicId());
        if(empOtherCont > CommonConstant.DEFAULT_0){
            throw new BusinessFailException("员工已经加入到其他诊所了！");
        }
        if(YesOrNoEnum.NO.getValue().equals(isAdmin)){
            if(StringUtil.isBlank(clinicEmp.getDeptId())){
                throw new BusinessFailException("请选择科室！");
            }
            if(CollectionUtils.isEmpty(clinicEmp.getRoleIdList())){
                throw new BusinessFailException("请选择员工角色");
            }
            Long roleCount = clinicAuthService.getRoleCount(clinicEmp.getRoleIdList(),clinicEmp.getClinicId());
            if(StringUtil.isBlank(roleCount) || roleCount.longValue() != clinicEmp.getRoleIdList().size()){
                throw new BusinessFailException("角色不存在或者角色已停用");
            }
            if(StringUtil.isBlank(clinicEmp.getIdCard())){
                throw new BusinessFailException("身份证号不能为空");
            }
            if(clinicEmp.getHireDate() == null){
                throw new BusinessFailException("入职日期不能为空");
            }
        }
        if(StringUtil.isNotBlank(clinicEmp.getTitle()) && clinicEmp.getTitle().length() > Constants.EMP_TITLE_LENGTH){
            throw new BusinessFailException("职称"+Constants.EMP_TITLE_LENGTH+"个字以内！");
        }
        if(!StringUtil.isBlank(clinicEmp.getDeptId())){
            ClinicDept clinicDept = clinicDeptService.getEnabledClinicDeptById(clinicEmp.getDeptId());
            if(clinicDept == null || !clinicDept.getClinicId().equals(clinicEmp.getClinicId())){
                throw new BusinessFailException("科室不存在");
            }
        }
        if(StringUtil.isNotBlank(clinicEmp.getCardNo())){
            //验证卡号格式
            if(!BankCardValidator.isValidBankCard(clinicEmp.getCardNo())){
                throw new BusinessFailException("工资卡号格式错误");
            }
        }
        if(StringUtil.isNotBlank(clinicEmp.getEmail())){
            //验证邮箱格式
            if(!EmailValidator.isValidEmail(clinicEmp.getEmail())){
                throw new BusinessFailException("邮箱格式错误");
            }
        }
        if(StringUtil.isNotBlank(clinicEmp.getIdCard())){
            if(!IdCardUtils.isValidFormat(clinicEmp.getIdCard())){
                throw new BusinessFailException("身份证号格式错误！");
            }
            Long cardEmpCount = getEmpCountByIdCard(clinicEmp.getClinicId(),clinicEmp.getEmpId(),clinicEmp.getIdCard());
            if(cardEmpCount > CommonConstant.DEFAULT_0){
                throw new BusinessFailException("当前身份证号已被占用，请更换身份证再试！");
            }
            //自动计算性别
            if(StringUtil.isBlank(clinicEmp.getGender())){
                String gender = IdCardUtils.extractGender(clinicEmp.getIdCard());
                if(StringUtil.isBlank(gender)){
                    gender = GenderEnum.UNKNOWN.getValue();
                }
                clinicEmp.setGender(gender);
            }
            if(clinicEmp.getSolarBirthday() == null){
                //自动计算阳历生日
                clinicEmp.setSolarBirthday(IdCardUtils.extractBirthDate(clinicEmp.getIdCard()));
            }
            if(clinicEmp.getLunarBirthday() == null){
                //自动计算阴历生日
                clinicEmp.setLunarBirthday(IdCardUtils.extractLunarBirthday(clinicEmp.getIdCard()));
            }
        }
        if(StringUtil.isNotBlank(clinicEmp.getHomeAddress())){
            if(clinicEmp.getHomeAddress().length() > Constants.EMP_ADDRESS_LENGTH){
                throw new BusinessFailException("家庭住址"+Constants.EMP_ADDRESS_LENGTH+"个字以内");
            }
        }
    }

    /**
     * 根据身份证查询员工数量
     * @param clinicId
     * @param empId
     * @param idCard
     * @return
     */
    public Long getEmpCountByIdCard(Long clinicId, Long empId, String idCard) {
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andIdCardEqualTo(idCard);
        criteria.andClinicIdEqualTo(clinicId);
        if(!StringUtil.isBlank(empId)){
            criteria.andEmpIdNotEqualTo(empId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return clinicEmpMapper.countByExample(example);
    }

    /**
     * 根据手机号查询员工数量
     * @param phone
     * @return
     */
    public Long getOtherEmpByPhone(String phone,Long clinicId){
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneEqualTo(phone);
        criteria.andIsEnabledEqualTo(YesOrNoEnum.YES.getValue());
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        if(!StringUtil.isBlank(clinicId)){
            criteria.andClinicIdNotEqualTo(clinicId);
        }
        return clinicEmpMapper.countByExample(example);
    }

    /**
     *
     * @param clinicId
     * @param empId
     * @param phone
     * @return
     */
    public Long getEmpCountByPhone(Long clinicId, Long empId, String phone){
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneEqualTo(phone);
        criteria.andClinicIdEqualTo(clinicId);
        if(!StringUtil.isBlank(empId)){
            criteria.andEmpIdNotEqualTo(empId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return clinicEmpMapper.countByExample(example);
    }

    /**
     * 员工编辑简介
     * @param clinicEmp
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateNotes(ClinicEmp clinicEmp) {
        if(StringUtil.isBlank(clinicEmp.getNotes())){
            throw new BusinessFailException("请输入简介！");
        }
        if(clinicEmp.getNotes().length() > Constants.EMP_NOTES_LENGTH){
            throw new BusinessFailException("简介"+Constants.EMP_NOTES_LENGTH+"个字以内！");
        }
        ClinicEmp dbClinicEmp = getEmpById(clinicEmp.getEmpId());
        if(dbClinicEmp == null){
            throw new BusinessFailException("员工不存在");
        }
        dbClinicEmp.setAvatarUrl(clinicEmp.getAvatarUrl());
        dbClinicEmp.setNotes(clinicEmp.getNotes());
        dbClinicEmp.setUpdateUserId(clinicEmp.getUpdateUserId());
        dbClinicEmp.setUpdateBy(clinicEmp.getUpdateBy());
        dbClinicEmp.setUpdateTime(new Date());
        clinicEmpMapper.updateByPrimaryKeySelective(dbClinicEmp);
    }

    /**
     * 修改
     * @param clinicEmp
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(ClinicEmpDTO clinicEmp) {
        ClinicEmp dbClinicEmp = getEmpById(clinicEmp.getEmpId());
        if(dbClinicEmp == null){
            throw new BusinessFailException("员工不存在");
        }
        validateEmp(clinicEmp,dbClinicEmp.getIsAdmin());
        clinicEmp.setIsAdmin(dbClinicEmp.getIsAdmin());
        if(YesOrNoEnum.YES.getValue().equals(dbClinicEmp.getIsAdmin())){
            //如果是管理员不能修改姓名和电话
            clinicEmp.setEmpName(dbClinicEmp.getEmpName());
            clinicEmp.setPhone(dbClinicEmp.getPhone());
            clinicEmp.setPassword(dbClinicEmp.getPassword());
        }else {
            if(!clinicEmp.getPhone().equals(dbClinicEmp.getPhone())){
                //如果修改了手机号，需要重置密码
                clinicEmp.setPassword(CryptoUtils.md5(Constants.DEFAULT_PASS));
            }else {
                clinicEmp.setPassword(dbClinicEmp.getPassword());
            }
        }
        clinicEmp.setUpdateTime(new Date());
        clinicEmpMapper.updateByPrimaryKeySelective(clinicEmp);
        //保存员工角色数据
        clinicAuthService.authUserRoles(clinicEmp);
    }


    /**
     * 删除
     * @param clinicEmp
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(ClinicEmp clinicEmp) {
        ClinicEmp dbClinicEmp = getEmpById(clinicEmp.getEmpId());
        if(dbClinicEmp == null){
            throw new BusinessFailException("员工不存在");
        }
        dbClinicEmp.setIsDelete(YesOrNoEnum.YES.getValue());
        dbClinicEmp.setUpdateUserId(clinicEmp.getUpdateUserId());
        dbClinicEmp.setUpdateBy(clinicEmp.getUpdateBy());
        dbClinicEmp.setUpdateTime(new Date());
        clinicEmpMapper.updateByPrimaryKeySelective(dbClinicEmp);
        //更新部门员工数量
        refreshEmpCount(clinicEmp.getClinicId(),clinicEmp.getDeptId());
    }

    /**
     * 启用
     * @param clinicEmp
     */
    @Transactional(rollbackFor = Exception.class)
    public void enable(ClinicEmp clinicEmp) {
        ClinicEmp dbClinicEmp = getEmpById(clinicEmp.getEmpId());
        if(dbClinicEmp == null){
            throw new BusinessFailException("员工不存在");
        }
        if(YesOrNoEnum.YES.getValue().equals(dbClinicEmp.getIsEnabled())){
            return;
        }
        dbClinicEmp.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbClinicEmp.setUpdateUserId(clinicEmp.getUpdateUserId());
        dbClinicEmp.setUpdateBy(clinicEmp.getUpdateBy());
        dbClinicEmp.setUpdateTime(new Date());
        clinicEmpMapper.updateByPrimaryKeySelective(dbClinicEmp);
    }

    /**
     * 停用
     * @param clinicEmp
     */
    @Transactional(rollbackFor = Exception.class)
    public void disable(ClinicEmp clinicEmp) {
        ClinicEmp dbClinicEmp = getEmpById(clinicEmp.getEmpId());
        if(dbClinicEmp == null){
            throw new BusinessFailException("员工不存在");
        }
        if(YesOrNoEnum.NO.getValue().equals(dbClinicEmp.getIsEnabled())){
            return;
        }
        dbClinicEmp.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbClinicEmp.setUpdateUserId(clinicEmp.getUpdateUserId());
        dbClinicEmp.setUpdateBy(clinicEmp.getUpdateBy());
        dbClinicEmp.setUpdateTime(new Date());
        clinicEmpMapper.updateByPrimaryKeySelective(dbClinicEmp);
    }




    /**
     * 查询员工账户
     * @param phone
     * @param password
     * @return
     */
    public ClinicEmp getEmpByAccount(String phone,String password){
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneEqualTo(phone);
        criteria.andPasswordEqualTo(CryptoUtils.md5(password));
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        criteria.andIsEnabledEqualTo(YesOrNoEnum.YES.getValue());
        List<ClinicEmp> clinicEmpList = clinicEmpMapper.selectByExample(example);
        return CollectionUtils.isEmpty(clinicEmpList) ? null : clinicEmpList.get(0);
    }

    public ClinicEmp getEmpById(Long empId){
        if(StringUtil.isBlank(empId)){
            return null;
        }
        ClinicEmp clinicEmp = clinicEmpMapper.selectByPrimaryKey(empId);
        if(clinicEmp == null || YesOrNoEnum.YES.getValue().equals(clinicEmp.getIsDelete())){
            return null;
        }
        return clinicEmp;
    }

    /**
     * 根据ID查询启用状态的员工
     * @param empId
     * @return
     */
    public ClinicEmp getEnabledEmpById(Long empId){
        ClinicEmp clinicEmp = getEmpById(empId);
        if(clinicEmp == null || YesOrNoEnum.NO.getValue().equals(clinicEmp.getIsEnabled())){
            return null;
        }
        return clinicEmp;
    }

    /**
     * 重置密码
     * @param resetPasswordDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(ResetPasswordDTO resetPasswordDTO) {
        ClinicEmp dbClinicEmp = null;
        if(PasswordChangeSourceEnum.OPERATION_BACKEND.getValue().equals(resetPasswordDTO.getSource())){
            //运营后台重置诊所管理员密码
            if(StringUtil.isBlank(resetPasswordDTO.getClinicId())){
                throw new BusinessFailException("诊所ID不能为空");
            }
            dbClinicEmp = getClinicAdmin(resetPasswordDTO.getClinicId());
            if(dbClinicEmp == null){
                throw new BusinessFailException("员工不存在");
            }
        }else if(PasswordChangeSourceEnum.ROLE_MANAGEMENT.getValue().equals(resetPasswordDTO.getSource())){
            //管理员重置员工密码
            if(StringUtil.isBlank(resetPasswordDTO.getNewPassword())){
                throw new BusinessFailException("新密码不能为空");
            }
            if(StringUtil.isBlank(resetPasswordDTO.getConfirmPassword())){
                throw new BusinessFailException("确认密码不能为空");
            }
            if(!resetPasswordDTO.getNewPassword().equals(resetPasswordDTO.getConfirmPassword())){
                throw new BusinessFailException("两次密码不一致！");
            }
            dbClinicEmp = getEnabledEmpById(resetPasswordDTO.getEmpId());
            if(dbClinicEmp == null){
                throw new BusinessFailException("员工不存在");
            }
            if(YesOrNoEnum.YES.getValue().equals(dbClinicEmp.getIsAdmin())){
                throw new BusinessFailException("没有权限！");
            }
        }else {
            //个人中心自助修改
            if(StringUtil.isBlank(resetPasswordDTO.getOldPassword())){
                throw new BusinessFailException("原密码不能为空");
            }
            if(StringUtil.isBlank(resetPasswordDTO.getNewPassword())){
                throw new BusinessFailException("新密码不能为空");
            }
            if(StringUtil.isBlank(resetPasswordDTO.getConfirmPassword())){
                throw new BusinessFailException("确认密码不能为空");
            }
            if(!resetPasswordDTO.getNewPassword().equals(resetPasswordDTO.getConfirmPassword())){
                throw new BusinessFailException("两次密码不一致！");
            }
            dbClinicEmp = getEnabledEmpById(resetPasswordDTO.getEmpId());
            if(dbClinicEmp == null){
                throw new BusinessFailException("员工不存在");
            }
            if(!dbClinicEmp.getPassword().equals(CryptoUtils.md5(resetPasswordDTO.getOldPassword()))){
                throw new BusinessFailException("原密码错误！");
            }
        }
        if(StringUtil.isBlank(resetPasswordDTO.getNewPassword())){
            dbClinicEmp.setPassword(CryptoUtils.md5(Constants.DEFAULT_PASS));
        }else {
            dbClinicEmp.setPassword(CryptoUtils.md5(resetPasswordDTO.getNewPassword()));
        }
        dbClinicEmp.setUpdateUserId(resetPasswordDTO.getUpdateUserId());
        dbClinicEmp.setUpdateBy(resetPasswordDTO.getUpdateBy());
        dbClinicEmp.setUpdateTime(new Date());
        clinicEmpMapper.updateByPrimaryKeySelective(dbClinicEmp);
    }

    /**
     * 查询部门下的员工数量
     * @param clinicId
     * @param deptId
     * @return
     */
    public long getEmpCount(Long clinicId, Long deptId) {
        ClinicEmpExample example = new ClinicEmpExample();
        ClinicEmpExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andDeptIdEqualTo(deptId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        long empCount = clinicEmpMapper.countByExample(example);
        return empCount;
    }


    /**
     * 更新部门数量
     * @param clinicId
     * @param deptId
     */
    @Transactional(rollbackFor = Exception.class)
    public void refreshEmpCount(Long clinicId, Long deptId) {
        if(StringUtil.isBlank(clinicId) || StringUtil.isBlank(deptId)){
            return;
        }
        long empCount = getEmpCount(clinicId,deptId);
        ClinicDept clinicDept = new ClinicDept();
        clinicDept.setDeptId(deptId);
        clinicDept.setEmpCount(Math.toIntExact(empCount));
        clinicDeptService.updateByPrimaryKeySelective(clinicDept);
    }

}
